package com.uh.microservice.core.util;

import com.uh.microservice.core.spring.SpringUtil;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.net.URL;
import java.util.List;

/**
 * Created by liming on 2017/9/26.
 */
public class CacheUtil {


    public static final String CACHE_NAME_SPACE_RATE_CACHE = "RATE_CACHE-";
    public static final String CACHE_NAME_SPACE_SYS_PARAM = "SYS_PARAM-";
    public static final String CACHE_NAME_SPACE_PAY_TYPE = "PAY_TYPE_CACHE";

    private static CacheUtil _instance=null;
    private CacheManager cacheManager ;// new CacheManager();
    private Cache cache ;//= cacheManager.getCache("local");

    private boolean isRedis=false;
    public static synchronized CacheUtil instance(){
        if(_instance==null)
            _instance=new CacheUtil();
        return _instance;
    }

    public CacheUtil(){
        if(SpringUtil.containProp("spring.redis.host"))
            isRedis=true;

        if(!isRedis) {
            Resource resource = new ClassPathResource("ehcache.xml");
            try {
                URL url = resource.getURL();
                cacheManager = new CacheManager(url);
                cache = cacheManager.getCache("local");
                cache.removeAll();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public Object getKey(String key){

            Element element = cache.get(key);
            if (element == null)
                return null;
            return element.getObjectValue();
    }

    public void putKey(String key,Object value){

            cache.put(new Element(key,value));
    }

    public void removeKey(String key){

            cache.remove(key);
    }

    public void refreshCacheManual(String key){
        if(!CACHE_NAME_SPACE_RATE_CACHE.equals(key) && !CACHE_NAME_SPACE_SYS_PARAM.equals(key)){
            return;
        }

            List<String> allKeys = cache.getKeys();
            allKeys.forEach(item -> {
                if (item.startsWith(key)) {
                    cache.remove(item);
                }
            });
    }

    public void clearCache(String key) {

            if (cache.isKeyInCache(key)) {
                cache.remove(key);
            }
    }
}
